package com.dc.annotation;

import cn.hutool.core.util.StrUtil;
import com.dc.util.RedisUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Component
public class SpringAnnotationScanner implements BeanPostProcessor {

    @Resource
    RedisUtil redisUtil;

    final String UNCHECKTOKEN = "uncheck:";

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if (methods != null) {
            for (Method method : methods) {
                UnCheckToken unCheckToken = AnnotationUtils.findAnnotation(method, UnCheckToken.class);
                if (null != unCheckToken) {
                    if (StrUtil.isNotBlank(unCheckToken.name()) && StrUtil.isNotBlank(unCheckToken.url())) {
                        String url = unCheckToken.name() + unCheckToken.url();
                        //将这个url存入redis
                        if(!redisUtil.hasKey(UNCHECKTOKEN + url)){
                            redisUtil.set(UNCHECKTOKEN + url, url);
                        }
                    }
                }
            }
        }
        return bean;
    }
}
